package com.sbtr.business.publishtask.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.business.auth.service.impl.RoleServiceImpl;
import com.sbtr.business.project.entity.AlgoPredictRecord;
import com.sbtr.business.project.entity.Project;
import com.sbtr.business.project.mapper.AlgoPredictRecordMapper;
import com.sbtr.business.project.service.impl.ProjectServiceImpl;
import com.sbtr.business.publishtask.entity.PublishAssignData;
import com.sbtr.business.publishtask.entity.PublishPredictTask;
import com.sbtr.business.publishtask.entity.PublishTaskData;
import com.sbtr.business.publishtask.mapper.PublishTaskDataMapper;
import com.sbtr.business.publishtask.process.ServerClientProcessor;
import com.sbtr.business.publishtask.service.IPublishPredictTaskService;
import com.sbtr.business.publishtask.service.IPublishTaskDataService;
import com.sbtr.business.trainingmodel.entity.TrainingModelData;
import com.sbtr.business.trainingmodel.service.ITrainingModelDataService;
import com.sbtr.business.trainingmodel.service.impl.TrainingModelDataServiceImpl;
import com.sbtr.business.trainingserver.entity.TrainingServer;
import com.sbtr.business.trainingserver.service.IPublishServerHttpApi;
import com.sbtr.business.trainingserver.service.impl.TrainingServerServiceImpl;
import com.sbtr.business.trainingtask.entity.TrainingInfo;
import com.sbtr.business.trainingtask.service.ITrainingInfoService;
import com.sbtr.business.user.service.IUserAllowCountService;
import com.sbtr.business.utils.OperatorUtil;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.common.ResultCodeCanstant;
import com.sbtr.common.file.CommonAnalyzeService;
import com.sbtr.common.file.dto.FileContentDto;
import com.sbtr.common.file.utils.AbstractNoModelDataListener;
import com.sbtr.constant.ProjectConstant;
import com.sbtr.exception.BDException;
import com.sbtr.exception.BizException;
import com.sbtr.open.publishtask.dto.*;
import com.sbtr.open.trainingmodel.dto.TrainingModelDataDto;
import com.sbtr.open.trainingserver.dto.TrainingServerDto;
import com.sbtr.open.user.dto.UserAllowCountDto;
import com.sbtr.util.BeanCopyUtils;
import com.sbtr.util.PageDtoUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 数据类部署任务表 服务实现类
 * </p>
 */
@Transactional
@Service
public class PublishTaskDataServiceImpl extends ServiceImpl<PublishTaskDataMapper, PublishTaskData>
        implements IPublishTaskDataService {

    private Logger logger = LoggerFactory.getLogger(PublishTaskDataServiceImpl.class);

    @Autowired
    private RoleServiceImpl roleService;

    @Autowired
    private PublishAssignDataServiceImpl publishAssignDataService;

    @Autowired
    private TrainingServerServiceImpl serverService;
    @Autowired
    private IPublishServerHttpApi publishServerHttpApi;
    @Autowired
    private TrainingModelDataServiceImpl trainingModelApi;
    @Autowired
    private ITrainingModelDataService trainingModelService;

    @Autowired
    AlgoPredictRecordMapper algoPredictRecordMapper;

    @Autowired
    OperatorUtil operatorUtil;
    @Autowired
    private ITrainingInfoService trainInfoService;

    @Autowired
    private IUserAllowCountService userAllowCountService;
    @Autowired
    private ProjectServiceImpl projectService;
    @Autowired
    private ServerClientProcessor serverClientProcessor;
    @Autowired
    private PublishPredictTaskServiceImpl publishPredictTaskService;

    @Value("${training-task.upload-file-dir}")
    private String uploadPath;

    @Autowired
    private CommonAnalyzeService commonAnalyzeService;

    @Override
    public Response<Boolean> publishModel(PublishTaskDataReqDto req) {
        // TODO Auto-generated method stub
        // 模型所在的项目是否已经有其他上线的模型
        TrainingModelData model = trainingModelService.getById(req.getModelId());
        Assert.isTrue(model != null, "模型不存在,模型id [" + req.getModelId() + "]");
        TrainingModelDataDto publishModel = trainingModelApi.findPublishByProject(model.getProjectId());
        Assert.isTrue(publishModel == null, "要替换新版本模型请先下线现有的模型");

        // 校验是否已经达到最大上线数量(管理员不需要校验)
        String userId = req.getCreater();
        if (StringUtils.isBlank(userId)) {
            userId = "test";
        }
        if (!roleService.isAdmin(userId)) {
            int userMaxCount = 1000;
            List<UserAllowCountDto> list = userAllowCountService.searchByUserIds(Arrays.asList(userId));
            if (list != null && !list.isEmpty()) {
                Integer maxCount = list.get(0).getUserMaxCount();
                userMaxCount = maxCount != null ? maxCount : userMaxCount;
            }
            // 查询用户账号的线上服务数量
            QueryWrapper<PublishTaskData> wrapper = new QueryWrapper<>();
            wrapper.eq("creater", userId);
            wrapper.eq("status", PublishTaskDataDto.TASK_STATUS_PUBLISHED);
            int onlineCount = this.count(wrapper);
            Assert.isTrue(onlineCount < userMaxCount, "当前账号发布模型上限为" + userMaxCount + "个,更多请联系管理员申请");
        }

        logger.info("处理模型发布start | req: {}", JSON.toJSONString(req));
        Long modelId = req.getModelId();
        if (null == modelId || modelId < 1) {
            logger.error("模型id参数不合法 | modelId: {}", modelId);
            return Response.error(ResultCodeCanstant.PARAMETER_ERROR.getValue(), "模型id参数不合法");
        }

        // 更改项目状态
//		Project project = projectService.getById(model.getProjectId());
//		String projectType = project.getProjectType();
        Boolean b = false;
        b = this.publishData(req);//发布模型请求
//		if (ProjectConstant.PROJECT_TYPE_DATA_PREDICT.equals(projectType)) {
//			b = this.publishData(req);//发布模型请求
//		} else {
//			logger.error("项目类型不合法 或未找到项目类型 |prjectId: {}", model.getProjectId());
//			return Response.error(ResultCodeCanstant.SYSTEN_ERROR.getValue(), "项目类型不合法 或未找到项目类型");
//		}
        logger.info("处理模型发布success | modelId: {}", modelId);

        // 更改项目状态  异步调用之后 不用维护
//		project.setProgressRate(ProjectConstant.PROJECT_STATUS_PUBLISHED);
//		project.setStatus(ProjectConstant.PROJECT_STATUS_PUBLISHED);

//		projectService.updateById(project);
        return Response.success(b);
    }

    private boolean publishData(PublishTaskDataReqDto req) {
        Long modelId = req.getModelId();
        logger.info("处理模型发布start | modelId: {}", modelId);

        // 1. 校验模型是否可以发布
        TrainingModelData model = validatePubish(req);


        // 2. 先新增任务，因为下面的步骤调用推理服务器，需要任务id
        PublishTaskData task = buildPublishTask(req);
        task.setProjectId(model.getProjectId());
        if (task.getId() != null) {
            baseMapper.updateById(task);
        } else {
            baseMapper.insert(task);
        }
        // 更新模型状态为已发布
        model.setStatus(TrainingModelDataDto.MODEL_STATUS_UNPUBLISH);
        trainingModelService.updateById(model);

        // 2. 走你，执行推理服务器的调用processor
        TrainingServer server;
        if (model.getIsExternalImport() == 1) {
            server = serverClientProcessor.publishModelData(model, task);//选择机器 发布任务
        } else {
            server = serverClientProcessor.publishExternalModel2(model, task);
        }


        // 3. 保存映射关系
        PublishAssignData assing = new PublishAssignData();
        assing.setTaskId(task.getId());
        assing.setServerId(server.getId());
        publishAssignDataService.save(assing);

//		model.setStatus(TrainingModelDataDto.MODEL_STATUS_PUBLISHED);
//		trainingModelService.updateById(model);

        //异步调用之后，状态由python维护
//		task.setStatus(PublishTaskDataDto.TASK_STATUS_PUBLISHED);
//		baseMapper.updateById(task);

        logger.info("处理模型发布success | modelId: {}", modelId);
        return true;
    }

    private PublishTaskData buildPublishTask(PublishTaskDataReqDto req) {
        PublishTaskData task = getNewestByModel(req.getModelId());
//		if (null != task) {
//			task.setTaskDesc(req.getTaskDesc());
//			task.setTaskName(req.getTaskName());
//		} else {
        task = BeanCopyUtils.copyProperties(req, PublishTaskData.class);
        task.setCreateTime(new Date());
//		}
        task.setPublishTime(new Date());
        task.setStatus(PublishTaskDataDto.TASK_STATUS_UNPUBLISH);
        return task;
    }

    /**
     * 校验模型是否能发布<br>
     * 校验的内容包括：该模型是否在发布、模型是否存在</br>
     * 如果校验不成功，抛出exception
     *
     * @param req - 请求参数
     * @return 校验成功后的模型数据队形
     * @author qiujun
     * @date 2019-10-29
     */
    private TrainingModelData validatePubish(PublishTaskDataReqDto req) {
//		if (StringUtils.isAnyBlank(req.getTaskName(), req.getTaskDesc())) {
//			logger.error("存在为空的请求参数 | req: {}", JSON.toJSONString(req));
//			throw new BizException("存在为空的请求参数");
//		}
        Long modelId = req.getModelId();
        if (null == modelId || modelId < 1) {
            logger.error("模型id参数不合法 | modelId: {}", modelId);
            throw new BizException("模型id参数不合法");
        }
        TrainingModelData model = trainingModelService.getById(modelId);
        if (null == model) {
            logger.error("模型数据不存在 | modelId: {}", modelId);
            throw new BizException("模型数据不存在");
        }
        List<PublishTaskData> taskList = baseMapper.listByModelStatus(modelId,
                PublishTaskDataDto.TASK_STATUS_PUBLISHED);
        if (!CollectionUtils.isEmpty(taskList)) {
            logger.error("该模型当前状态已发布 | modelId: {}", modelId);
            throw new BizException("该模型当前状态已发布");
        }
        return model;
    }

    /**
     * 通过模型id，获取一条最新的记录<br>
     * 如果查询的结果有多条符合，那最近的一条返回<br>
     * 因为模型id可能未曾发布过，查询的结果可能为空<br>
     * 方法不会校验模型是否存在且合法
     *
     * @param modelId - 模型id
     * @return
     * @author qiujun
     * @date 2019-10-29
     */
    private PublishTaskData getNewestByModel(Long modelId) {
        return baseMapper.getNewestByModel(modelId);
    }

    @Override
    public PublishTaskDataDto findById(Long id) {
        // TODO Auto-generated method stub
        return BeanCopyUtils.copyProperties(getById(id), PublishTaskDataDto.class);
    }


    @Override
    public PublishTaskDataDto findByProjectId(Long projectId) {
        // TODO Auto-generated method stub
        QueryWrapper<PublishTaskData> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", projectId);
        List<PublishTaskData> list = this.list(wrapper);
        if (list != null && !list.isEmpty()) {
            return BeanCopyUtils.copyProperties(list.get(0), PublishTaskDataDto.class);
        }
        return null;
    }


    @Override
    public PageDto<PublishTaskDataDto> search(String taskName, Long currPage, Long pageSize, Long projectId) {
        // TODO Auto-generated method stub
        IPage<PublishTaskData> page = new Page<>();
        if (currPage != null) {
            page.setCurrent(currPage);
        }
        if (pageSize != null) {
            page.setSize(pageSize);
        }
        QueryWrapper<PublishTaskData> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(taskName)) {
            wrapper.like("task_name", taskName);
        }
        if (projectId != null) {
            wrapper.eq("project_id", projectId);
        }
//		if (!roleService.isAdmin(UserUtils.getFdLoginName())) {
//			wrapper.eq("creater", UserUtils.getFdLoginName());
//		}
        wrapper.orderByDesc("id");
        page = page(page, wrapper);
        PageDto<PublishTaskDataDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, PublishTaskDataDto.class);
        this.setModelNameAndProjectName(pageDto.getList());

        return pageDto;
    }

    private void setModelNameAndProjectName(List<PublishTaskDataDto> list) {
        // 查询模型名称和项目名称
        if (list != null && !list.isEmpty()) {
            List<Long> modelIdList = new ArrayList<>();
            list.forEach(p -> modelIdList.add(p.getModelId()));
            QueryWrapper<TrainingModelData> mWrapper = new QueryWrapper<>();
            mWrapper.in("id", modelIdList);
            List<TrainingModelData> modelList = trainingModelApi.list(mWrapper);
            if (modelList != null && !modelList.isEmpty()) {
                List<Long> projectIdList = new ArrayList<>();
                for (TrainingModelData model : modelList) {
                    projectIdList.add(model.getProjectId());
                    for (PublishTaskDataDto dto : list) {
                        if (dto.getModelId().equals(model.getId())) {
                            dto.setModelName(model.getModelName());
                            dto.setProjectId(model.getProjectId());
                            break;
                        }
                    }
                }

                QueryWrapper<Project> pWrapper = new QueryWrapper<>();
                pWrapper.in("id", projectIdList);
                List<Project> projectList = projectService.list(pWrapper);
                if (projectList != null && !projectList.isEmpty()) {
                    for (PublishTaskDataDto dto : list) {
                        for (Project project : projectList) {
                            if (dto.getProjectId().equals(project.getId())) {
                                dto.setProjectName(project.getProjectName());
                                dto.setAppId(project.getAppId());
                                dto.setAppKey(project.getAppKey());
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public boolean deleteById(@PathVariable("id") Long id) {
        // TODO Auto-generated method stub
        PublishTaskData task = getById(id);
        Assert.isTrue((task != null
                && task.getCreater() != null), "权限不足");
        String status = task.getStatus();
        if (PublishTaskDataDto.TASK_STATUS_PUBLISHED.equals(status)) {
            logger.warn("id为[{}]的部署任务状态为[{}],不能删除", id, status);
            return false;
        }
        return removeById(id);
    }

    @Override
    public boolean stopTask(Long id) {
        // TODO Auto-generated method stub
        PublishTaskData task = getById(id);
        if (task != null) {
            String status = task.getStatus();
            if (PublishTaskDataDto.TASK_STATUS_UNPUBLISH.equals(status)) {
                logger.warn("id为[{}]的部署任务状态为[{}],不需要停止", id, status);
                throw new RuntimeException("任务已经是下线状态");
            }

            // 根据部署任务id找出任务所在的服务器(部署任务分配表)
            QueryWrapper<PublishAssignData> wrapper = new QueryWrapper<>();
            wrapper.eq("task_id", id);
            List<PublishAssignData> assignList = publishAssignDataService.list(wrapper);
            if (assignList == null || assignList.isEmpty()) {
                logger.warn("id为[{}]的部署任务没有部署到服务器", id);
                throw new RuntimeException("没有找到任务所部署的服务器");
            }
            // 查询服务器列表
            List<Long> serverIdList = new ArrayList<>();
            assignList.forEach(l -> serverIdList.add(l.getServerId()));
            QueryWrapper<TrainingServer> wrapper2 = new QueryWrapper<>();
            wrapper2.in("id", serverIdList);
            List<TrainingServer> serverList = serverService.list(wrapper2);
            if (serverList == null || serverList.isEmpty()) {
                logger.warn("id为[{}]的部署任务没有找到部署服务器信息", id);
                throw new RuntimeException("没有找到任务所部署的服务器");
            }
            TrainingModelData model = trainingModelService.getById(task.getModelId());
            if (model == null) {
                logger.warn("id为[{}]的模型没有找到对应模型", id);
                throw new RuntimeException("模型没有找到对应模型");
            }
            Project project = projectService.getById(model.getProjectId());
            String projectType = project.getProjectType();
            boolean tag = false;
            for (TrainingServer trainingServer : serverList) {
                if (TrainingServerDto.TRAINING_SERVER_STATUS_OFFLINE.equals(trainingServer.getStatus())) {
                    throw new RuntimeException("服务器已下线");
                }

                tag = publishServerHttpApi
                        .stopTaskData(BeanCopyUtils.copyProperties(trainingServer, TrainingServerDto.class), id);
                logger.info("ip为[{}]部署服务器下线id为[{}]的部署任务,状态为[{}]", trainingServer.getIp(), id, tag);

            }
            if (tag) {
                // 清除关联关系
                publishAssignDataService.remove(wrapper);
                // 修改任务状态
                task.setStatus(PublishTaskDataDto.TASK_STATUS_UNPUBLISH);
                // 修改模型状态
                if (model != null) {
                    model.setApi("项目模型未上线，暂无API地址");
                    model.setStatus(TrainingModelDataDto.MODEL_STATUS_UNPUBLISH);
                    trainingModelService.updateById(model);
                }
                // 计算运行时间
                if (task.getPublishTime() != null) {
                    long runningTime = (new Date().getTime() - task.getPublishTime().getTime()) / 1000;
                    task.setRunningTime(
                            task.getRunningTime() == null ? runningTime : runningTime + task.getRunningTime());
                }
                // 修改项目状态
//				project.setProgressRate(ProjectConstant.PROJECT_PROGRESS_PUBLISH);//下线任务时进度不用修改
                project.setStatus(ProjectConstant.PROJECT_STATUS_UNPUBLISH);
                projectService.updateById(project);

            }
            return saveOrUpdate(task) && tag;
        }
        logger.warn("找不到id为[{}]的部署任务", id);
        return false;
    }

    @Override
//	public List<PredictDataResultDto> predictData(@PathVariable("id") Long id, @RequestBody PredictDataReqDto reqDto) {
    public List<PredictDataResultDto> predictData(Long id, PredictNewDto reqDto) {

        // TODO Auto-generated method stub
        List<PredictDataResultDto> result = new ArrayList<>();
        PublishTaskData task = getById(id);
        Long modelId = task.getModelId();
        TrainingModelData trainingModelData = trainingModelService.getById(modelId);
        Long trainTaskId = trainingModelData.getTaskId();

//		TrainingTaskData trainingTaskData = trainingTaskDataService.getById(trainTaskId);
        TrainingInfo trainingInfo = trainInfoService.getById(trainTaskId);

        if (task != null) {
            String status = task.getStatus();
            if (PublishTaskDataDto.TASK_STATUS_UNPUBLISH.equals(status)) {
                logger.warn("id为[{}]的部署任务状态为[{}],不能进行预测", id, status);
                throw new RuntimeException("任务已经是下线状态");
            }
            // 根据部署任务id找出任务所在的服务器(部署任务分配表)
            QueryWrapper<PublishAssignData> wrapper = new QueryWrapper<>();
            wrapper.eq("task_id", id);
            List<PublishAssignData> assignList = publishAssignDataService.list(wrapper);
            if (assignList == null || assignList.isEmpty()) {
                logger.warn("id为[{}]的部署任务没有部署到服务器", id);
                throw new RuntimeException("没有找到任务所部署的服务器");
            }
            // 查询服务器列表
            List<Long> serverIdList = new ArrayList<>();
            assignList.forEach(l -> serverIdList.add(l.getServerId()));
            QueryWrapper<TrainingServer> wrapper2 = new QueryWrapper<>();
            wrapper2.in("id", serverIdList);
            List<TrainingServer> serverList = serverService.list(wrapper2);
            if (serverList == null || serverList.isEmpty()) {
                logger.warn("id为[{}]的部署任务没有找到部署服务器信息", id);
                throw new RuntimeException("没有找到任务所部署的服务器");
            }
            // 暂时按单节点处理,选取第一个服务器
            if (TrainingServerDto.TRAINING_SERVER_STATUS_OFFLINE.equals(serverList.get(0).getStatus())) {
                throw new RuntimeException("服务器已下线");
            }


            JSONArray predictResult = publishServerHttpApi.predictData(
                    BeanCopyUtils.copyProperties(serverList.get(0), TrainingServerDto.class), id,
                    reqDto.getPredictData());

            if (predictResult != null && !predictResult.isEmpty()) {
                if ("1005".equals(trainingInfo.getType())) {
                    JSONObject predictData = reqDto.getPredictData().getJSONObject(0);
                    PredictDataResultDto pddto = new PredictDataResultDto(predictData, predictResult);
                    result.add(pddto);
                } else {
                    for (int i = 0; i < predictResult.size(); i++) {
                        JSONObject predictData = reqDto.getPredictData().getJSONObject(i);
                        Object presult = predictResult.get(i);
                        PredictDataResultDto pddto = new PredictDataResultDto(predictData, presult);
                        result.add(pddto);
                    }
                }
            } else {
                // 调用失败次数
                task.setFailCount(
                        task.getFailCount() == null || task.getFailCount() == 0 ? 1 : task.getFailCount() + 1);
            }
            // 调用总次数
            task.setTotalCount(
                    task.getTotalCount() == null || task.getTotalCount() == 0 ? 1 : task.getTotalCount() + 1);
            saveOrUpdate(task);
        }

        return result;
    }

//	@Override
//	@RequestMapping(value = "/{id}/predict-data-multi-create", method = RequestMethod.POST)
//	public PublishPredictTaskDto predictDataMultiCreate(@PathVariable("id") Long id,
//			@RequestBody PredictDataMultiReqDto req) {
//		// TODO Auto-generated method stub
//		String creater = req.getCreater();
//		String fileName = req.getFileName();
//
//		// 先处理上传的文件
//		if (!fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx")
//
//				&& !fileName.toLowerCase().endsWith(".txt") && !fileName.toLowerCase().endsWith(".csv")) {
//			logger.error(fileName + " 上传文件不是excel,csv,txt");
//			throw new RuntimeException(fileName + " 上传文件不是excel,csv,txt");
//		}
//		PublishPredictTaskDto dto = new PublishPredictTaskDto();
//
//		Assert.isTrue(StringUtils.isNotBlank(creater), "用户账号不能为空");
//		PublishTaskDataDto publishTaskDataDto = this.findById(id);
//
//		dto.setCreater(creater);
//		dto.setPredictFile(fileName);
//		dto.setPublishId(id);
//		dto.setTaskName(id.toString() + creater + fileName);
//		dto.setStatus(PublishPredictTaskDto.PREDICT_NOT_START);
//		dto.setProjectId(publishTaskDataDto.getProjectId());
//		dto.setCreateTime(new Date());
//		dto = publishPredictTaskService.save(dto);
//		return dto;
//	}


    @Override
    public PublishPredictTaskDto predictDataMultiCreate(Long id,
                                                        PredictDataMultiNewDto req) {
        // TODO Auto-generated method stub
        String creater = req.getCreater() == null ? "test" : req.getCreater();
        String fileName = req.getFileOssName();

        String bucketName = req.getBucketDir();
        // 先处理上传的文件
        if (!fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx")
                && !fileName.toLowerCase().endsWith(".txt") && !fileName.toLowerCase().endsWith(".csv")
                && !fileName.toLowerCase().endsWith(".zip")) {
            logger.error(fileName + " 上传文件不是excel,csv,txt,zip");
            throw new RuntimeException(fileName + " 上传文件不是excel,csv,txt,zip");
        }
        PublishPredictTaskDto dto = new PublishPredictTaskDto();

        Assert.isTrue(StringUtils.isNotBlank(creater), "用户账号不能为空");
        PublishTaskDataDto publishTaskDataDto = this.findById(id);


        // 更改项目状态
        Project project = projectService.getById(publishTaskDataDto.getProjectId());
        String projectType = project.getProjectType();

        dto.setCreater(creater);
        dto.setPredictFile(bucketName + "/" + fileName);//+projectType+"/"+creater+"/"
        dto.setPublishId(id);


        if (projectType.equals("img_classify")) {
            dto.setTaskName("图像分类 " + projectType + creater + fileName);
        } else if (projectType.equals("voice_classify")) {
            dto.setTaskName("声音分类 " + projectType + creater + fileName);
        } else if (projectType.equals("txt_classify")) {
            dto.setTaskName("文本分类 " + projectType + creater + fileName);
        } else if (projectType.equals("data_predict")) {
            dto.setTaskName("数据预测 " + projectType + creater + fileName);
        } else if (projectType.equals("img_detection")) {
            dto.setTaskName("物体检测 " + projectType + creater + fileName);
        } else if (projectType.equals("data_unsupervised")) {
            dto.setTaskName("无监督 " + projectType + creater + fileName);
        } else if (projectType.equals("other")) {
            dto.setTaskName("模型导入类型 " + projectType + creater + fileName);
        } else if (projectType.equals("matlab")) {
            dto.setTaskName("Matlab  " + projectType + creater + fileName);
        }

        dto.setStatus(PublishPredictTaskDto.PREDICT_NOT_START);
        dto.setProjectId(publishTaskDataDto.getProjectId());
        dto.setCreateTime(new Date());
        dto = publishPredictTaskService.save(dto);
        return dto;
    }


    @Override
//	public void predictDataMulti(@PathVariable("id") Long id, @RequestBody PublishPredictTaskDto dto) {
    public JSONObject predictDataMulti(Long id, PredictDataMultiNewDto dto
    ) throws InterruptedException {
        // TODO Auto-generated method stub
        PublishPredictTaskDto dtos = publishPredictTaskService.findById(dto.getId());
        PublishPredictTask task = BeanCopyUtils.copyProperties(dtos, PublishPredictTask.class);
        Long publishId = task.getPublishId();
        task.setStatus(PublishPredictTaskDto.PREDICT_RUNNING);
        task.setStartTime(new Date());
        publishPredictTaskService.saveOrUpdate(task);

        // 检测服务器是否可以使用
        PublishTaskData publishTaskData = this.getById(publishId);
        if (publishTaskData == null) {
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("任务未部署或者一下线");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("任务未部署或者一下线");
        }
        String status = publishTaskData.getStatus();
        if (PublishTaskDataDto.TASK_STATUS_UNPUBLISH.equals(status)) {
            logger.warn("id为[{}]的部署任务状态为[{}],不能进行预测", publishId, status);
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("任务已经是下线状态");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("任务已经是下线状态");
        }
        // 根据部署任务id找出任务所在的服务器(部署任务分配表)
        QueryWrapper<PublishAssignData> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", publishId);
        List<PublishAssignData> assignList = publishAssignDataService.list(wrapper);
        if (assignList == null || assignList.isEmpty()) {
            logger.warn("id为[{}]的部署任务没有部署到服务器", publishId);
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("id为[" + publishId + "]的部署任务没有部署到服务器");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("没有找到任务所部署的服务器");
        }
        // 查询服务器列表
        List<Long> serverIdList = new ArrayList<>();
        assignList.forEach(l -> serverIdList.add(l.getServerId()));
        QueryWrapper<TrainingServer> wrapper2 = new QueryWrapper<>();
        wrapper2.in("id", serverIdList);
        List<TrainingServer> serverList = serverService.list(wrapper2);
        if (serverList == null || serverList.isEmpty()) {
            logger.warn("id为[{}]的部署任务没有找到部署服务器信息", publishId);
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("id为[" + publishId + "]的部署任务没有找到部署服务器信息");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("没有找到任务所部署的服务器");
        }
        // 暂时按单节点处理,选取第一个服务器
        if (TrainingServerDto.TRAINING_SERVER_STATUS_OFFLINE.equals(serverList.get(0).getStatus())) {
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("服务器已下线");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("服务器已下线");
        }

        AbstractNoModelDataListener abstractNoModelDataListener = new AbstractNoModelDataListener(commonAnalyzeService, new HashMap<>());
        EasyExcel.read(dto.getBucketDir() + "/" + dto.getFileOssName(), abstractNoModelDataListener).sheet().doRead();

        FileContentDto fileContentDto = new FileContentDto();
        fileContentDto.setContent(abstractNoModelDataListener.resultDataList);
        fileContentDto.setTitle(abstractNoModelDataListener.titleList);

        AbstractNoModelDataListener abstractNoModelDataListener2 = new AbstractNoModelDataListener(commonAnalyzeService, new HashMap<>());
        EasyExcel.read(dto.getBucketDir() + "/" + dto.getFileOssName(), abstractNoModelDataListener2).sheet(1).doRead();

        FileContentDto fileContentDto2 = new FileContentDto();
        fileContentDto2.setContent(abstractNoModelDataListener2.resultDataList);
        fileContentDto2.setTitle(abstractNoModelDataListener2.titleList);
        JSONArray arrayR = new JSONArray();
        JSONObject r = new JSONObject();
        List<LinkedHashMap<String, String>> linkedHashMaps = fileContentDto.getListMap();
        List<List<String>> linkedHashMaps2 = fileContentDto2.getListList();
        if (dto.getDiagnoseType() == 1 && (CollectionUtils.isEmpty(linkedHashMaps2) || CollectionUtils.isEmpty(linkedHashMaps2.get(0)))) {
            throw new BDException("缺少sheet2真实值");
        }

        for (int j = 0; j < linkedHashMaps.size(); j++) {
            JSONArray array = new JSONArray();
            LinkedHashMap<String, Double> param = new LinkedHashMap<>();
            for (Map.Entry<String, String> p : linkedHashMaps.get(j).entrySet()) {
                if (StringUtils.isNotBlank(p.getValue())) {
                    param.put(p.getKey(), Double.valueOf(p.getValue()));
                }
            }
            if (dto.getDiagnoseType() == 1) {
                Double real = linkedHashMaps2.get(j).get(0) == null ? 0d : Double.parseDouble(linkedHashMaps2.get(j).get(0));
                param.put("label", real);
            }

            array.add(JSONUtil.parseObj(param));

            JSONArray predictResult = publishServerHttpApi.predictData(
                    BeanCopyUtils.copyProperties(serverList.get(0), TrainingServerDto.class), id,
                    array);

            arrayR.add(predictResult.get(0));
            Thread.sleep(10);
        }
        String bucketDir = uploadPath + "/outPredictRecord";

        String fileName = "诊断记录文件.xlsx";
        String otherName = UUID.randomUUID().toString().replaceAll("-", "") + ".xlsx";

        File pathFile = new File(bucketDir);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }

        if (dto.getDiagnoseType() == 1) {
            List<LinkedHashMap<String, String>> result = new ArrayList<>();
            int passCount = 0;
            for (int i = 0; i < fileContentDto.getListList().size(); i++) {
                LinkedHashMap<String, String> resultMap = new LinkedHashMap<String, String>();
                String real = linkedHashMaps2.get(i).get(0);
                String predict = String.valueOf(arrayR.get(i));
                String pass = real.equals(predict) ? "通过" : "不通过";
                if (real.equals(predict)) passCount++;
                resultMap.put("real", real);
                resultMap.put("predict", predict);
                resultMap.put("pass", pass);
                result.add(resultMap);
            }
            BigDecimal rate = new BigDecimal(passCount).divide(new BigDecimal(fileContentDto.getListList().size()), 2, RoundingMode.UP);
            r.put("rate", rate.doubleValue());
            r.put("list", result);

            try (
                    OutputStream os = Files.newOutputStream(Paths.get(bucketDir + "/" + otherName));
            ) {
                List<String> title = new ArrayList<>();
                title.add("真实值");
                title.add("预测值");
                title.add("是否通过");
                List<String> title2 = new ArrayList<>();
                title2.add("real");
                title2.add("predict");
                title2.add("pass");
                EasyExcel.write(os).head(operatorUtil.changeExportHead(title)).sheet(fileName).doWrite(operatorUtil.getArrayData(result, false, title2));
                AlgoPredictRecord algoPredictRecord = new AlgoPredictRecord();
                algoPredictRecord.setPath(bucketDir + "/" + otherName);
                algoPredictRecord.setName(fileName);
                algoPredictRecord.setTaskId(id);
                algoPredictRecordMapper.insert(algoPredictRecord);
            } catch (Exception e) {
                throw new BDException(e.getMessage());
            }
        } else {
            r.put("title", fileContentDto.getTitle());
            r.put("predictResult", arrayR);
            r.put("list", fileContentDto.getListList());

            fileContentDto.getTitle().add("predictResult");
            for (int i = 0; i < fileContentDto.getListList().size(); i++) {
                fileContentDto.getContent().get(i).put(fileContentDto.getContent().get(i).size(),arrayR.get(i).toString());
            }

            try (
                    OutputStream os = Files.newOutputStream(Paths.get(bucketDir + "/" + otherName));
            ) {
                EasyExcel.write(os).head(operatorUtil.changeExportHead(fileContentDto.getTitle())).sheet(fileName).doWrite(operatorUtil.getArrayData(fileContentDto.getListMap(), false, fileContentDto.getTitle()));
                AlgoPredictRecord algoPredictRecord = new AlgoPredictRecord();
                algoPredictRecord.setPath(bucketDir + "/" + otherName);
                algoPredictRecord.setName(fileName);
                algoPredictRecord.setTaskId(id);
                algoPredictRecordMapper.insert(algoPredictRecord);
            } catch (Exception e) {
                throw new BDException(e.getMessage());
            }

        }

        return r;


//        boolean predictResult = publishServerHttpApi.predictBigData(
//                BeanCopyUtils.copyProperties(serverList.get(0), TrainingServerDto.class), id,
//                dto.getId().toString());


/*

		task.setTotalRowData(predictData.size());
		publishPredictTaskService.saveOrUpdate(task);
		List<String[]> predcitDataResult = predictDataMultiProcessor.predict(task, publishTaskData, serverList.get(0),
				predictData);
		String fileName = task.getPredictFile();
		Long currentMills = System.currentTimeMillis();
		int dotIndex = fileName.lastIndexOf(".");
		String resultName = fileName.substring(0, dotIndex);
		String predictResultFileName = "predict-" + publishId.toString() + "-" + currentMills.toString() + "-"
				+ resultName + ".csv";
		File predictFile = new File(uploadPath, predictResultFileName);
		// try {
		// ExcelReader.write(predcitDataResult, predictFile);
		//
		// } catch (Exception e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
		// task.setError("保存分析结果失败");
		// task.setEndTime(new Date());
		// publishPredictTaskService.saveOrUpdate(task);
		// throw new RuntimeException("保存分析结果失败");
		// }

		Boolean writeSuccess = TxtUtil.exportCsv(predictFile, predcitDataResult);
		if (!writeSuccess) {
			task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
			task.setError("保存分析结果失败");
			task.setEndTime(new Date());
			publishPredictTaskService.saveOrUpdate(task);
			throw new RuntimeException("保存分析结果失败");
		}

		task.setPredictPrecent(1);
		task.setStatus(PublishPredictTaskDto.PREDICT_COMPLETE);
		task.setResultFile(predictResultFileName);
		task.setEndTime(new Date());
		publishPredictTaskService.saveOrUpdate(task);
		dtos = BeanCopyUtils.copyProperties(task, PublishPredictTaskDto.class);
		*/
    }


    /*@Override
    @RequestMapping(value = "/{id}/predict-data-multi", method = RequestMethod.POST)
//	public void predictDataMulti(@PathVariable("id") Long id, @RequestBody PublishPredictTaskDto dto) {
    public void predictDataMulti(@PathVariable("id") Long id, @RequestBody PredictDataMultiNewDto dto
    ) {
        // TODO Auto-generated method stub
        PublishPredictTaskDto dtos = publishPredictTaskService.findById(dto.getId());
        PublishPredictTask task = BeanCopyUtils.copyProperties(dtos, PublishPredictTask.class);
        Long publishId = task.getPublishId();
        task.setStatus(PublishPredictTaskDto.PREDICT_RUNNING);
        task.setStartTime(new Date());
        publishPredictTaskService.saveOrUpdate(task);

//		MaterialInfoDto materialInfoDto = materialInfoApi.findById(dto.getFileId());


//		List<String[]> predictData = predictDataMultiProcessor.readFileData(task);
        List<String[]> predictData = predictDataMultiProcessor.readFileDataFromMinio(task,dto);

        if (predictData != null && predictData.size() < 2) {
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("上传的文件不能够为空，或只包含标题行，注意默认文件第一行为标题");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("上传的文件不能够为空，或只包含标题行，注意默认文件第一行为标题");
        }

        // 检测服务器是否可以使用
        PublishTaskData publishTaskData = this.getById(publishId);
        if (publishTaskData == null) {
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("任务未部署或者一下线");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("任务未部署或者一下线");
        }
        String status = publishTaskData.getStatus();
        if (PublishTaskDto.TASK_STATUS_UNPUBLISH.equals(status)) {
            logger.warn("id为[{}]的部署任务状态为[{}],不能进行预测", publishId, status);
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("任务已经是下线状态");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("任务已经是下线状态");
        }
        // 根据部署任务id找出任务所在的服务器(部署任务分配表)
        QueryWrapper<PublishAssignData> wrapper = new QueryWrapper<>();
        wrapper.eq("task_id", publishId);
        List<PublishAssignData> assignList = publishAssignDataService.list(wrapper);
        if (assignList == null || assignList.isEmpty()) {
            logger.warn("id为[{}]的部署任务没有部署到服务器", publishId);
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("id为[" + publishId + "]的部署任务没有部署到服务器");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("没有找到任务所部署的服务器");
        }
        // 查询服务器列表
        List<Long> serverIdList = new ArrayList<>();
        assignList.forEach(l -> serverIdList.add(l.getServerId()));
        QueryWrapper<TrainingServer> wrapper2 = new QueryWrapper<>();
        wrapper2.in("id", serverIdList);
        List<TrainingServer> serverList = serverService.list(wrapper2);
        if (serverList == null || serverList.isEmpty()) {
            logger.warn("id为[{}]的部署任务没有找到部署服务器信息", publishId);
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("id为[" + publishId + "]的部署任务没有找到部署服务器信息");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("没有找到任务所部署的服务器");
        }
        // 暂时按单节点处理,选取第一个服务器
        if (TrainingServerDto.TRAINING_SERVER_STATUS_OFFLINE.equals(serverList.get(0).getStatus())) {
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("服务器已下线");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("服务器已下线");
        }
        task.setTotalRowData(predictData.size());
        publishPredictTaskService.saveOrUpdate(task);
        List<String[]> predcitDataResult = predictDataMultiProcessor.predict(task, publishTaskData, serverList.get(0),
                predictData);
        String fileName = task.getPredictFile();
        Long currentMills = System.currentTimeMillis();
        int dotIndex = fileName.lastIndexOf(".");
        String resultName = fileName.substring(0, dotIndex);
        String predictResultFileName = "predict-" + publishId.toString() + "-" + currentMills.toString() + "-"
                + resultName + ".csv";
        File predictFile = new File(uploadPath, predictResultFileName);
        // try {
        // ExcelReader.write(predcitDataResult, predictFile);
        //
        // } catch (Exception e) {
        //
        // e.printStackTrace();
        // task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
        // task.setError("保存分析结果失败");
        // task.setEndTime(new Date());
        // publishPredictTaskService.saveOrUpdate(task);
        // throw new RuntimeException("保存分析结果失败");
        // }

        Boolean writeSuccess = TxtUtil.exportCsv(predictFile, predcitDataResult);
        if (!writeSuccess) {
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("保存分析结果失败");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("保存分析结果失败");
        }

        try {
            ossUtil.putObject(predictResultFileName, predictFile);
            ossUtil.deleteObject(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            task.setStatus(PublishPredictTaskDto.PREDICT_ERROR);
            task.setError("分析结果上传到OSS时操作失败了");
            task.setEndTime(new Date());
            publishPredictTaskService.saveOrUpdate(task);
            throw new RuntimeException("分析结果上传到OSS时操作失败了");
        }
//		task.setPredictPrecent(1);
//		task.setStatus(PublishPredictTaskDto.PREDICT_COMPLETE);
//		task.setResultFile(predictResultFileName);
        task.setEndTime(new Date());
        publishPredictTaskService.saveOrUpdate(task);
        dtos = BeanCopyUtils.copyProperties(task, PublishPredictTaskDto.class);
    }

*/
    @Override
    public PublishTaskDataDto findByModel(Long modelId) {
        // TODO Auto-generated method stub
        QueryWrapper<PublishTaskData> wrapper = new QueryWrapper<>();
        wrapper.eq("model_id", modelId);
        wrapper.orderByDesc("create_time");
        List<PublishTaskData> list = this.list(wrapper);
        if (list != null && !list.isEmpty()) {
            return BeanCopyUtils.copyProperties(list.get(0), PublishTaskDataDto.class);
        }
        return null;
    }

    @Override
    public JSONArray getPredictJSON(Long id) {
        // TODO Auto-generated method stub
        QueryWrapper<PublishTaskData> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        wrapper.orderByDesc("create_time");
        List<PublishTaskData> list = this.list(wrapper);
        if (list.size() == 0) {
            throw new RuntimeException("没有task_id: " + id + " 的在线预测任务");
        }
        PublishTaskData publishTaskData = list.get(0);
        Long modelId = publishTaskData.getModelId();
        TrainingModelDataDto trainingModelDto = trainingModelApi.findById(modelId);
        if (trainingModelDto == null) {
            throw new RuntimeException("没有task_id: " + id + " 的模型相关信息没有找到");
        }
        String classifier = trainingModelDto.getClassifier();
        JSONObject classifierJSON = JSONObject.parseObject(classifier);

        if (classifierJSON.containsKey("feature") && classifierJSON.containsKey("feature_name")) {
            JSONObject featureObject = classifierJSON.getJSONObject("feature");
            JSONArray featureNameArray = classifierJSON.getJSONArray("feature_name");
            List<String> featureNameList = featureNameArray.toJavaList(String.class);

            List<String> dateNameList = null;
            if (classifierJSON.containsKey("date_name")) {
                JSONArray dateNameArray = classifierJSON.getJSONArray("date_name");
                dateNameList = dateNameArray.toJavaList(String.class);
            } else {
                dateNameList = new ArrayList<String>();
            }

            JSONObject exampleJSON = new JSONObject(true);
            for (String featureName : featureNameList) {
                if (featureObject.containsKey(featureName)) {
                    exampleJSON.put(featureName, "str");
                } else if (dateNameList.contains(featureName)) {
                    exampleJSON.put(featureName, "date");
                } else {
                    exampleJSON.put(featureName, 0);
                }
            }
            JSONArray exampleArray = new JSONArray();
            exampleArray.add(exampleJSON);
            return exampleArray;
        } else {
            throw new RuntimeException("模型表classifier数据缺失");
        }
    }

/*
	@Override
	@RequestMapping(value = "/{id}/get-predict-data-multi-template", method = RequestMethod.GET)
	public String getPredictDataMultiTemplate(@PathVariable("id") Long id,
			@RequestParam(name = "fileType", required = false) String fileType) {
		// TODO Auto-generated method stub
		QueryWrapper<PublishTaskData> wrapper = new QueryWrapper<>();
		wrapper.eq("id", id);
		wrapper.orderByDesc("create_time");
		List<PublishTaskData> list = this.list(wrapper);
		if (list.size() == 0) {
			throw new RuntimeException("没有task_id: " + id + " 的在线预测任务");
		}
		PublishTaskData publishTaskData = list.get(0);
		Long modelId = publishTaskData.getModelId();
		TrainingModelDataDto trainingModelDto = trainingModelApi.findById(modelId);
		if (trainingModelDto == null) {
			throw new RuntimeException("没有task_id: " + id + " 的模型相关信息没有找到");
		}
		String classifier = trainingModelDto.getClassifier();
		JSONObject classifierJSON = JSONObject.parseObject(classifier);

		if (classifierJSON.containsKey("feature") && classifierJSON.containsKey("feature_name")) {
			JSONObject featureObject = classifierJSON.getJSONObject("feature");
			JSONArray featureNameArray = classifierJSON.getJSONArray("feature_name");
			List<String> featureNameList = featureNameArray.toJavaList(String.class);

			List<String> dateNameList = null;
			if (classifierJSON.containsKey("date_name")) {
				JSONArray dateNameArray = classifierJSON.getJSONArray("date_name");
				dateNameList = dateNameArray.toJavaList(String.class);
			} else {
				dateNameList = new ArrayList<String>();
			}
			// JSONObject exampleJSON = new JSONObject();
			List<String> titleData = new ArrayList<String>();
			List<String> valueData = new ArrayList<String>();
			for (String featureName : featureNameList) {
				if (featureObject.containsKey(featureName)) {
					titleData.add(featureName);
					valueData.add("str");
				} else if (dateNameList.contains(featureName)) {
					titleData.add(featureName);
					valueData.add("date");
				} else {
					titleData.add(featureName);
					valueData.add("0");
				}
			}

			List<String[]> templateData = new ArrayList<String[]>();
			templateData.add(titleData.toArray(new String[titleData.size()]));
			templateData.add(valueData.toArray(new String[valueData.size()]));

			// 如果但fileType为空的时候，默认返回为csv
			if (fileType == null) {
				fileType = "csv";
			}

			// 生成文件名
			String fileName = id.toString() + "_predict_template_" + System.currentTimeMillis() + "." + fileType;
			if (!"xlsx".equals(fileType) && !"xls".equals(fileType) && !"txt".equals(fileType)
					&& !"csv".equals(fileType)) {
				throw new RuntimeException("保存的文件类型不支持");
			}
			File f = new File(uploadPath, fileName);
			f.deleteOnExit();

			// 开始保存的相关操作
			if ("xlsx".equals(fileType) || "xls".equals(fileType)) {
				try {
					ExcelReader.write(templateData, f);
				} catch (Exception e) {

					e.printStackTrace();
					throw new RuntimeException("保存文件失败");
				}
			} else if ("csv".equals(fileType)) {
				Boolean writeSuccess = TxtUtil.exportCsv(f, templateData);
				if (!writeSuccess) {
					throw new RuntimeException("保存文件失败");
				}
			} else if ("txt".equals(fileType)) {
				boolean writeSuccess = TxtUtil.exportTxt(f, templateData);
				if (!writeSuccess) {
					throw new RuntimeException("保存文件失败");
				}
			} else {
				throw new RuntimeException("保存的文件类型不支持");
			}

			try {
				ossUtil.putObject(fileName, f);
			} catch (Exception e) {
				e.printStackTrace();
				throw new RuntimeException("预测模板获取失败");
			}

			String url = ossUtil.getObjectUrl(fileName);

			if (url == null) {
				throw new RuntimeException("预测模板获取失败");
			}
			return url;
		} else {
			throw new RuntimeException("模型表classifier数据缺失");
		}
	}

*/
//	@Override
//	public String getPublishTaskType(Long id) {
//		// TODO Auto-generated method stub
//		PublishTaskData publishTaskData = this.getById(id);
//		TrainingModelData trainingModelData = trainingModelApi.getById(publishTaskData.getModelId());
//		TrainingTaskData trainingTaskData = trainingTaskDataService.getById(trainingModelData.getTaskId());
//		return trainingTaskData.getType();
//	}

}
